<?php
/**
 * Created by PhpStorm.
 * User: chinanet
 * Date: 2020-01-05
 * Time: 16:14
 */

namespace Francis\PayHelper;

class RSA256Helper
{
    /****
     * RSA2签名 RSA sign
     * @param $data string  pre-sign string
     * @param $private_key_path string  private_key_path
     * @return string 签名结果
     */
    public static function rsaSHA256Sign($data, $private_key_path) {
        $fp = fopen($private_key_path, "r");
        $priv_key = fread($fp, filesize($private_key_path));
        fclose($fp);
        $pkeyid = openssl_get_privatekey($priv_key);

        // compute signature
        openssl_sign($data, $signMsg, $pkeyid,OPENSSL_ALGO_SHA256);

        // free the key from memory
        openssl_free_key($pkeyid);

        $signMsg = base64_encode($signMsg);
        return $signMsg;
    }



    public static function rsaSHA256Verify($data, $ali_public_key_path, $sign) {
        $pubKey = file_get_contents($ali_public_key_path);
        $res = openssl_get_publickey($pubKey);
        $result = openssl_verify($data, base64_decode($sign), $res,OPENSSL_ALGO_SHA256);
        openssl_free_key($res);
        return $result;
    }
}